<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import {Login} from "@/api/admin.js";
import {useUserStore} from "@/stores/user.js";
import {useRouter} from "vue-router";

const router = useRouter();
const userStore = useUserStore();
const loginForm = ref({
  username: "",
  password: "",
});

const formRef = ref();

const rules = {
  username: [{required: true, message: "请输入用户名", trigger: "blur"}],
  password: [{required: true, message: "请输入密码", trigger: "blur"}],
};

const handleLogin = () => {
  console.log(loginForm.value);
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await Login({
        username: loginForm.value.username,
        password: loginForm.value.password,
      });
      ElMessage.success( "登录成功");
      userStore.setToken(res.data);
      router.push({ path: "/" });
    }
  });
};
</script>

<template>
<div class="login-container">
  <el-card class="login-card">
    <h2 class="login-title">管理员登录</h2>
    <el-form :model="loginForm" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" placeholder="请输入密码" type="password" show-password/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f0f2f5;
}

.login-card {
  width: 400px;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}
</style>
